package com.hybao.login.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hybao.service.login.LoginService;

@Controller
@RequestMapping("/login/taobao")
public class TaobaoLoginController {
	private final String taobaoContainer = "http://container.open.taobao.com/container?appkey=12241124";
	private final String mainurl = "/main.html";
	private Logger log = Logger.getLogger(TaobaoLoginController.class.getName());
	@Autowired
	private LoginService loginService;
	
	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody Map<String,String> taobaoLogin(HttpServletRequest request, HttpServletResponse response) {
		//String top_sign = request.getParameter("top_sign");
		String top_parameters = request.getParameter("top_parameters");
		String top_session = request.getParameter("top_session");
		Map<String, String> topParams = convertBase64StringtoMap(top_parameters);
		try {
			if (topParams == null) {
				response.sendRedirect(taobaoContainer);
				return null;
			}
			String nick = topParams.get("visitor_nick");
			boolean res = loginService.chenckUser(nick, top_session,response);
			if(!res){
				try {
					response.sendRedirect(taobaoContainer);
					return null;
				} catch (IOException e) {
					log.error("top login failed");
				}
			}
			response.sendRedirect(mainurl);
		} catch (IOException e) {
			log.error("top login failed");
		}
		return null;
	}
	
	private Map<String, String> convertBase64StringtoMap(String str) {
		if (str == null){
			return null;
		}
//		BASE64Decoder decoder = new BASE64Decoder();
		String keyvalues = null;
		try {
			keyvalues = new String(Base64.decodeBase64(URLDecoder.decode(str, "utf-8").getBytes("utf-8")));
//			keyvalues = new String(decoder.decodeBuffer(str),"GBK");
		} catch (IOException e) {
			return null;
		}

		if (keyvalues == null || keyvalues.length() == 0)
			return null;
		String[] keyvalueArray = keyvalues.split("&");
		Map<String, String> map = new HashMap<String, String>();
		for (String keyvalue : keyvalueArray) {
			String[] s = keyvalue.split("=");
			if (s == null || s.length != 2)
				return null;
			map.put(s[0], s[1]);
		}

		return map;
	}
	
	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
}
